<template>
  <el-dialog
    title="设置角色权限"
    :visible.sync="dialogVisible"
    width="30%"
    :show-close="false"
    :close-on-click-modal="false"
  >
    <label>角色名：</label>
    <el-input v-model="roleInfo.roleName" style="width:200px; margin-left:20px" disabled />
    <p></p>
    <el-tree
      :data="data"
      show-checkbox
      node-key="menuId"
      ref="tree"
      :default-expand-all="true"
      :default-checked-keys='defaultCheckedId'
      :props="defaultProps"
    ></el-tree>

    <span slot="footer" class="dialog-footer">
      <el-button @click="cancle">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { Message } from "element-ui";
import arrToTree from '../../../../utils/arrToTree'
export default {
  props: ["role"],
  data() {
    return {
      checkMenuId: [],
      defaultCheckedId: [], //树形控件默认勾选
      roleInfo: null,
      dialogVisible: true,
      // closeVisible:false,
      data: [],
      defaultProps: {
        children: "children",
        label: "menuName",
        id: "menuId",
      },
    };
  },
  methods: {
    cancle() {
      this.$emit("closeDialog", false);
    },
    submit() {
      let arr = [];
      arr = this.$refs.tree.getCheckedNodes();
      let arrId = [];
      for (let i = 0; i < arr.length; i++) {
        arrId.push(arr[i].menuId);
      }
      const p = new URLSearchParams();
      p.append("roleId", this.roleInfo.roleId);
      p.append("menuIds", arrId);
      this.$http({
        method: "post",
        url: "/roleMenu/insertRoleMenu",
        data: p,
      }).then((res) => {
        if (res.data > 0) {
          Message({ message: "设置成功", type: "success" });
        } else {
          Message({ message: "设置失败", type: "error" });
        }
      });
      this.$emit("closeDialog", false);
    },
    menuList() {
      const that = this;
      that.$http.get("/menu/getAllMenu").then((res) => {
        const a = arrToTree.arraytotree(res.data);
        that.data = a;
      });
    },
  },
  mounted() {
    this.menuList();   
    console.log(this.roleInfo.roleId)
     this.$http.get("/roleMenu/selectRoleMenuByRoleId",{params:{roleId:this.roleInfo.roleId}})
     .then(res=>{
      this.defaultCheckedId=res.data
     })
  },
  watch: {
    role: {
      handler(nval, oval) {
        this.roleInfo = nval;
      },
      immediate: true,
      deep: true,
    },
  },
};
</script>
<style lang='less' scoped>
</style>